【发布时间】:2022-01-23 13:05:03
【问题描述】:
刚开始为我的一项任务探索模板功能,我需要根据模板中的类型名添加一些操作。有人能指出这种结构有什么问题吗:
#include <iostream>
#include <type_traits>
using namespace std;
template <typename T>
T foo()
{
if(std::is_same<T, int>::value)
{
return 2;
}
if(std::is_same<T, std::string>::value)
{
return "apple";
}
}
int main()
{
std::cout<<"foo is: "<<foo<int>()<<std::endl;
return 0;
}
我想知道:
- 为什么这个错误会发生
main.cpp:23:16: error: invalid conversion from ‘const char*’ to ‘int’以及如何摆脱它? - 有没有更好的方法根据提供给函数的
typename来执行特定的操作?
更新:
原来我的程序使用的是低于 C++17 的编译器
尝试:
我尝试了另一种方法来处理这种情况,但失败了:
#include <iostream>
#include <type_traits>
using namespace std;
template <typename T, typename U>
T foo()
{
T t = U;
return t;
}
int main()
{
std::cout<<"foo is: "<<foo<int, 1>()<<std::endl;
return 0;
}
谁能指出这里出了什么问题?
【问题讨论】: