在 C++ 中鸭子键入(通过其非类型模板参数的值专门化模板函数)
duck typing in C++ (specialize a template function by the value of its non-type template parameter)
要进行一种鸭子打字,我确实
template<bool b>
struct A{
static template<typename V> f1(V*, [other params]);
static template<typename V> f2(V*, [other params]);
};
template<> template<typename T>
void A<false>::f1(V*, [other params]){}
template<> template<typename T>
void A<true>::f1(V*, [other params]){
...some code...
}
template<int flags>
struct V{
void f(){
A<flags&Some compile time conditions>::f1 (this,[params]);
A<flags&Some compile time conditions>::f2 (this,[params]);
}
};
你认为有没有更优雅的解决方案,不是模板类,函数专业化(我不想在函数中添加额外的参数)
我想做类似的事情
template<int X> struct C{
void f(){std::cout<<"C::f"<<std::endl;};
};
template<> struct C<0>{
};
template<int X> struct D{
C<X> c;
template<bool b>
void f();
void g(){
f<X!=0>();
}
};
template<>
template<int X>
void D<X>::f<true>{
c.f();
};
template<int X>
template<>
void D<X>::f<false>{};
int main(){
D<3> ch;
ch.g();
D<0> cn;
cn.g();
}
但这不是有效的代码,我收到错误:模板 ID "f"用作声明符。
有没有办法通过其非类型模板参数的值来专门化模板函数?
template<>
template<int X>
void D<X>::f<true>(){
c.f();
};
template<int X>
template<>
void D<X>::f<false>(){};
这是非法的(所有尝试都是非法的)。专用化成员函数模板时,它的封闭类也必须专用。
但是,您可以通过将函数包装在采用其模板参数的模板化结构中来轻松克服这个问题。类似的东西
template <int X, bool B>
struct DXF;
template <int X>
struct DXF<X, true>
{
static void f() { // B is true!
}
};
template <int X>
struct DXF<X, false>
{
static void f() { // B is false!
}
};
并用DXF<X, (X!=0)>::f()
调用它.
但是,似乎您只想专攻X==0
.在这种情况下,您可以专注于:
template <>
void D<0>::f() {}
请注意,在这种情况下,f
不是成员模板。
您可以选择的另一个选择是重载。您可以将int
包装在某个模板的参数列表中,如下所示:
template<int X> struct D{
C<X> c;
void f(std::true_type*) { ... true code ... }
void f(std::false_type_*) { ... false code ... }
void g(){
f((std::integral_constant<bool, X!=0>*)0);
}
请注意,true_type和false_type只是std::integral_constant<bool, true>
和false
的typedef
,或者。
相关文章:
- 扩展C++生成的代码的模板参数类型名称
- 如何在 c++ 中定义接受不同参数类型的函数向量?
- 在 C++ 中运行时调用模板时,是否可以切换模板的参数类型?
- 将函数参数类型声明为 auto
- 将函数的参数 - 签名从使用 'std::function<T>' 转换为模板参数类型
- 在 C++17 中调用具有不同参数类型的构造函数
- 具有先前参数类型匹配的参数包
- 我想知道为什么"std::unique_ptr<int> foo(新 int)"是合法的,因为"std::<int>unique_ptr"要求输入参数类型应该是"int"?
- 将可变参数类型列表的扩展打包为复杂类型的初始值设定项列表 - 合法吗?
- MSVC 错误:4 个重载中的任何一个都无法转换所有参数类型
- 使用constexpr + auto作为返回和参数类型的奇怪类型推导
- 如何从第一个参数推断第二个参数类型?
- C++模板函数中,指定回调函子/lambda 的参数类型,同时仍允许内联?
- 如何用不同的参数类型和数字回调函数
- C++stoi:这两个重载都无法转换所有参数类型
- 为什么std::{container}::template不能推导其参数类型
- 为模板参数类型中的新对象分配内存
- 为指向成员模板参数的指针推导额外模板参数类型的紧凑方式
- 使用std::conditional中的模板来确定函数参数类型
- C++中的短参数类型