我有一個模板函式應該執行不同的代碼,具體取決于型別。簡化的函式如下所示:
template<typename T>
std::string test(T value)
{
std::string v;
if(std::is_arithmetic<T>())
{
v = std::to_string(value);
}
else
{
v = std::string(value);
}
return v;
}
用法:
test("Hello");
test(123);
但我收到此錯誤:
In instantiation of void test(T) [with T = const char*]:
error: no matching function for call to to_string(const char*)
note: candidate: std::string std::__cxx11::to_string(int) <near match>
to_string(int __val)
and the same for the following:
to_string(unsigned __val)
to_string(long __val)
to_string(unsigned long __val)
好的,我知道在這種情況下,例如const char *編譯將失敗,因為沒有std::to_string(const char *). 但我怎樣才能使代碼有效?只需要注意,在我的真實代碼中,我限制為c 11.
uj5u.com熱心網友回復:
您現在可以了解為什么if constexpr要添加到語言中。如果您需要在更大的演算法中執行某些型別相關的操作,那么在 C 17 之前的方法通常是通過標記調度
namespace detail {
template<typename T>
std::string stringify(T value, std::true_type) {
return std::to_string(value);
}
template<typename T>
std::string stringify(T value, std::false_type) {
return std::string(value);
}
}
template<typename T>
std::string test(T value)
{
std::string v;
v = detail::stringify(value, std::is_arithmetic<T>());
return v;
}
這是在兩個條件下分派,但該技術可以擴展到多個多載,具體取決于您如何構造標簽型別。標準中的一個常見示例是迭代器類別。
uj5u.com熱心網友回復:
您可以使用SFINAE應用多載。例如
// for arithmetic types
template<typename T>
typename std::enable_if<std::is_arithmetic<T>::value, std::string>::type test(T value)
{
std::string v;
v = std::to_string(value);
return v;
}
// for non-arithmetic types
template<typename T>
typename std::enable_if<!std::is_arithmetic<T>::value, std::string>::type test(T value)
{
std::string v;
v = std::string(value);
return v;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/351960.html
