vla*_*don 1 c++ templates template-specialization c++11
我需要做这个魔术:
我有一个模板:
template <class T>
void Foo(const T& value)
Run Code Online (Sandbox Code Playgroud)
但我需要它专门为简单类型,例如bool,int等则其将被常量的值,而不是常量引用传递:
template <>
void Foo<bool>(const bool value)
template <>
void Foo<int>(const int value)
// and so on, including std::nullptr_t
template <>
void Foo<std::nullptr_t>(std::nullptr_t)
{
// some special behavior
}
Run Code Online (Sandbox Code Playgroud)
但它无法编译.
怎么做正确?
如果所有基本类型和指针的功能相同,我猜你可以使用std :: is_fundamental,std :: is_pointer和std :: enable_if:
template<typename T>
std::enable_if_t<std::is_fundamental<T>::value || std::is_pointer<T>::value>
foo(const T) {
std::cout << __PRETTY_FUNCTION__ << std::endl;
}
template<typename T>
std::enable_if_t<!std::is_fundamental<T>::value && !std::is_pointer<T>::value>
foo(const T&) {
std::cout << __PRETTY_FUNCTION__ << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
关于wandbox的示例
| 归档时间: |
|
| 查看次数: |
283 次 |
| 最近记录: |