所以我想做2个功能:一个用于数字(带有模板),另一个用于字符串。这是我的最佳尝试:
标题:
class myIO
{
public:
template<class Arithmetic,
class = enable_if_t< is_arithmetic_v <Arithmetic>>
>
static Arithmetic Input();
template<>
static string Input<string, void>();
};
cpp:
template<class Arithmetic, class>
static Arithmetic myIO::Input()
{
Arithmetic x;
//...
return x;
}
template<>
static string myIO::Input<string, void>()
{
string x;
//...
return x;
}
此实现有效,但如果我想将其与string
一起使用,则必须执行string x = myIO::Input<string, void>();
而且我想只写<string>
而不是<string, void>
有可能吗?
您可以做这样的事情
#include <iostream>
#include <string>
class A {
public:
template<typename T, typename U>
static void func()
{
std::cout << "Do stuff\n";
}
template<typename T>
static void func()
{
A::func<T, void>();
}
};
int main()
{
A::func<string>();
return 0;
}
这里是答案:。h:
class myIO
{
public:
template<class Arithmetic,
class = enable_if_t< is_arithmetic_v <Arithmetic>>
>
static Arithmetic Input();
template<class String,
class = enable_if_t< is_same_v<String, string> >
>
static string Input();
};
。cpp:
template<class Arithmetic, class>
static Arithmetic myIO::Input()
{
Arithmetic x;
// doing something
return x;
}
template<class String, class>
static string myIO::Input()
{
string x;
// doing something
return x;
}
p.s。我实际上已经尝试过类似的方法-enable_if_t< typeid(String) == typeid(string), string >
-但没有用