【问题标题】:Calling a variadic template function gives error C2660 in Visual Studio 2015在 Visual Studio 2015 中调用可变参数模板函数会出现错误 C2660
【发布时间】:2016-11-18 19:33:54
【问题描述】:

以下代码在 Visual Studio 2015 社区中出现 C2660 错误:

class Logger {
public:
    template <class T> void writeLine(const T& value) {
        if (this->filestream.is_open()) {
            filestream << object << std::endl;
        }
    }

    template <typename T> void write(const T& value) {
        if (this->filestream.is_open()) {
            filestream << value;
        }
    }

    template <typename T, typename... Targs> void write(const T& value, const Targs&... args) {
        if (this->filestream.is_open()) {
            filestream << value;
            this->write(args...);
        }
    }

    // ... singleton stuff
}

我这样调用函数:

#define LOG(x) Logger::instance().write(__FILE__, " (line ", __LINE__, "): ", x, std::endl);

这是输出日志中的错误:

encoder.cpp(51): error C2660: 'Logger::write': function does not take 6 arguments

【问题讨论】:

    标签: c++ visual-studio-2015 variadic-templates


    【解决方案1】:

    问题在于std::endl 本身就是一个模板

    template< class CharT, class Traits >
    std::basic_ostream<CharT, Traits>& endl( std::basic_ostream<CharT, Traits>& os );
    

    因此可能的解决方案是

    var.write(__FILE__, " (line ", __LINE__, "): ", 22, std::endl<char, std::char_traits<char>>);
    

    关于这个问题的更多信息here

    【讨论】:

      【解决方案2】:

      std::endl 是一个模板,编译器没有足够的信息来选择合适的特化。有很多方法可以避开这一点:

      • 使用std::endl&lt;char,std::char_traits&lt;char&gt;&gt; 作为您的最终论点(糟糕)。
      • 使用'\n',这显然不是等效的,但可能会起作用。
      • 创建一个专门的Logger::endl 并发送它。

      可以在here 找到后者的一个不错的例子。


      无关,您可能应该考虑使用完美转发。调整您的模板成员这样做应该很简单。

      template <typename T>
      void write(T&& value) {
          if (this->filestream.is_open()) {
              filestream << std::forward<T>(value);
          }
      }
      
      template <typename T, typename... Args>
      void write(T&& value, Args&&... args)
      {
          this->write(std::forward<T>(value));
          this->write(std::forward<Args>(args)...);
      }
      

      请参见此处:Advantages of using forward,以及链接文章,The Forwarding Problem。

      【讨论】:

      • 我永远不会猜到std::endl 会造成问题。我使用了第一个解决方案,并且效果很好。为什么完美的转发代码更好用?
      • @AliAliDoust 有很多关于转发问题的很好的参考资料,以及完美的转发如何解决它。请参阅此处:Advantages of using forward,以及链接文章,The Forwarding Problem。他们会比我解释得更好。
      猜你喜欢
      • 1970-01-01
      • 2013-01-26
      • 2021-10-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-11
      • 1970-01-01
      • 2016-07-24
      • 1970-01-01
      相关资源
      最近更新 更多