2017-03-08 7 views
0

を使用しているときに 'T'から 'const char *'への変換がありません。コンソールとファイルの両方にstuffを出力する演算子< <チェーンを使用するクラスがあります。同時に。行が壊れたときはいつでもそれをフラッシュする必要があります。これは、定義されたendl(\ nで置き換えられます)で起こります。このコードは動作せず、多くのエラーを吐き出します(Tからconst char *への変換はありません)。なにが問題ですか?std :: is_same <T、const char *> ::値

#pragma once 
#include <iostream> 
#include <fstream> 


/*class declaration*/ 

template <typename T> 
inline Logger & Logger::operator<<(const T &a) 
{ 
    if (debug::enabled) 
    { 
     std::cout << a; 
     file << a; 
     if (this->previousLineBroken) 
     { 
      std::cout << std::flush; 
      file << std::flush; 
      this->previousLineBroken = false; 
     } 
     if (std::is_same<T, const char*>::value) { 
      this->previousLineBroken = (a == debug::endl); 
     } 
     return *this; 
    } 
} 

削除のconst(定数T & a)はちょうどより多くのエラーと物事が悪化します。

UPD: previousLineBrokenはboolで、debug :: endlはconst char * = "\ n"です。

//debug.h 
    #pragma once 
    #define logger *logPtr 
    #include "Classes.h" 
    #include "logger.h" 
    namespace debug 
    { 
     static const char* endl = "\n"; 
     static const bool enabled = true; 
    } 
    using debug::endl; 
+0

'previousLineBroken'と' debug :: endl'の種類は何ですか? –

+0

@static_cats boolとconst char * – AdmiralMyxtaR

答えて

4

あなたif文は、そのため、コンパイラが

std::is_same<T, const char*>::value 

false場合でも、任意のTため

this->previousLineBroken = (a == debug::endl); 

をコンパイルしようと、コンパイル時分岐ではありません。このである可能性があります。質問にMCVEを追加する必要があります。 C++ 17では


、あなたはif constexprを使用してifコンパイル時のブランチを行うことができます。

C++ 11では
if constexpr(std::is_same<T, const char*>::value) { 
    this->previousLineBroken = (a == debug::endl); 
} 

、あなたは追加のヘルパー関数を使用することができますそしてではなくをオーバーロード:

template <typename T> 
void setPreviousLineBroken(std::true_type, T a) 
{ 
    this->previousLineBroken = (a == debug::endl); 
} 

template <typename T> 
void setPreviousLineBroken(std::false_type, T) { /* do nothing */ } 

あなたのコードがします次のようになります:

template <typename T> 
inline Logger & Logger::operator<<(const T &a) 
{ 
    if (debug::enabled) 
    { 
     std::cout << a; 
     file << a; 
     if (this->previousLineBroken) 
     { 
      std::cout << std::flush; 
      file << std::flush; 
      this->previousLineBroken = false; 
     } 
     setPreviousLineBroken(std::is_same<T, const char*>{}); 
     return *this; 
    } 
} 
+0

const char *の専用関数を作成する以外は、C++ 14ではこれを実行できません。 – AdmiralMyxtaR

+0

@AdmiralMyxtaR:あなた自身の 'static_if'を実装することができます。私は[CppCon 2016でこのことについて話をしました](https://www.youtube.com/watch?v=aXSsUqVSe2k) –

関連する問題