首先,代码受限于C++11,因此我无法利用if constexpr
下面是我的示例代码片段:
class A{
public:
int a;
int b;
}
class B{
public:
int key;
int val;
}
class C{
public:
int n1;
int n2;
}
class D{
public:
int n1;
int n2;
}
class E{
public:
int n1;
int n2;
}
template<typename T>
void func1(T data) {
if (T == type(A)) { // Just pseudo template-check code
std::cout<<data.a<<data.b; //<------1
} else if (T == type (B)) { // Just pseudo template-check code
std::cout<<data.key<<data.val; //<------2
} else {
std::cout<<data.n1<<data.n2; //<------3
}
int main() {
A a;
B b;
C c;
D d;
E e;
func1(a);
func1(b);
func1(c);
func1(d);
func1(e);
return 0;
}
当前,我在以下位置得到一个编译时错误,
1: B,D,E,F has no member a & b
&
2: A,D,E,F has no member key & val
&
3. A, B has no member n1 & n2
我尝试使用is_same()&; 也是这样,但我每次都得到相同的编译时错误。
编辑了代码以突出模板的需要。
您可以使用函数重载而完全避免使用函数模板。
void func1(A a)
{
// Type dependent code.
}
void func1(B a)
{
// Type dependent code.
}
只有当对其进行函数调用的所有类型都有公共代码时,函数模板才有意义。 如果您有一些对所有类型通用的代码和一些依赖于类型的代码,那么您可以使用:
void func1(A a)
{
// Type dependent code.
}
void func1(B a)
{
// Type dependent code.
}
template <typename T>
void func2(T t)
{
// Type independent code.
}
template <typename T>
void func(T obj)
{
func1(obj); // Call function that uses type dependent code.
func2(obj); // Call function that uses type independent code.
}
您必须为要与之一起使用的两种类型编写函数的专门化。
#include<iostream>
class A{
public:
int a;
int b;
};
class B{
public:
int key;
int val;
};
template<typename T>
void func1(T);
template<>
void func1<A>(A arg) {
std::cout<<"A"<<std::endl;
std::cout<<arg.a<<arg.b;
}
template<>
void func1<B>(B arg) {
std::cout<<"B"<<std::endl;
std::cout<<arg.key<<arg.val;
}
int main(){
A a;
func1(a);
B b;
func1(b);
}
简单的过载就可以了。
template <typename T>
void func1(T data)
{
std::cout << data.n1 << data.n2;
}
void func1(A data)
{
std::cout << data.a << data.b;
}
void func1(B data)
{
std::cout << data.key << data.val;
}
https://godbolt.org/z/r7ee6e
稍微调整了一下:https://godbolt.org/z/xxpwae