相关疑难解决方法(0)

元编程:函数定义失败定义了一个单独的函数

这个答案中,我根据类型的is_arithmetic属性定义了一个模板:

template<typename T> enable_if_t<is_arithmetic<T>::value, string> stringify(T t){
    return to_string(t);
}
template<typename T> enable_if_t<!is_arithmetic<T>::value, string> stringify(T t){
    return static_cast<ostringstream&>(ostringstream() << t).str();
}
Run Code Online (Sandbox Code Playgroud)

dyp建议,不是is_arithmetic类型的属性,是否to_string为类型定义是模板选择标准.这显然是可取的,但我不知道如何说:

如果std::to_string未定义,则使用ostringstream重载.

声明to_string标准很简单:

template<typename T> decltype(to_string(T{})) stringify(T t){
    return to_string(t);
}
Run Code Online (Sandbox Code Playgroud)

这与我无法弄清楚如何构建的标准相反.这显然不起作用,但希望它传达了我正在尝试构建的内容:

template<typename T> enable_if_t<!decltype(to_string(T{})::value, string> (T t){
    return static_cast<ostringstream&>(ostringstream() << t).str();
}
Run Code Online (Sandbox Code Playgroud)

c++ templates result-of sfinae template-meta-programming

26
推荐指数
4
解决办法
2030
查看次数

了解c ++中的模板

我正在尝试运行以下程序,但它会生成编译错误:

#ifndef TEMPLATE_SUM_H_
#define TEMPLATE_SUM_H_

template<typename T>
class sum
{
  public:
    sum() {
      val_1 = 0;
      val_2 = 0;
    }
    sum(T a, T b) {
      val_1 = a;
      val_2 = b;
    }
    friend std::ostream& operator<<(std::ostream &, const sum<> &);

  private:
    T val_1, val_2;
    T result() const;
};

#endif
Run Code Online (Sandbox Code Playgroud)

源文件:

include <iostream>
#include "inc/sum.h"

template<typename T>
T sum<T>::result() const {
   return (val_1 + val_2);
}

template<typename T>
std::ostream& operator<<(std::ostream& os, const sum<T>& obj) {
//std::ostream& operator<<(std::ostream& os, sum<T>& obj) {
  os …
Run Code Online (Sandbox Code Playgroud)

c++ templates

1
推荐指数
1
解决办法
306
查看次数