我有兴趣为仅针对特定数据类型的通用类定义自定义方法。我不确定什么是实现它的好方法。如果将其放在类之外,则将无法访问类变量,因此我认为我永远无法使它以这种方式工作。如果我将其放置在类中,则意味着它适用于任何T类型,而不仅仅是特定类型。通过定义代码的通用版本并仅发送该类型作为我感兴趣的输入,我已经能够使代码以后一种方式工作,但是有没有更整齐的方法来实现此目的?
下面是一些代码,以使其清楚
#include<iostream>
#include<string>
using namespace std;
template<typename T>
class abc
{
public:
void myvoid();
};
template<typename string>
void abc<string>::myvoid()
{
cout<<"This portion should execute only if an instance of class is called with a string parameter" ;
}
int main()
{
abc<int> int1;
abc<string> string1;
string1.myvoid(); //should work good
int1.myvoid(); //shouldnt execute myvoid
}
static_assert
如果所讨论的方法使用了错误的类型,则可以使用它来防止编译:
#include <type_traits> // for std::is_same
template <typename T>
struct Foo
{
void foo() const {}
void bar() const
{
static_assert(std::is_same<T, int>::value, "T is not int");
}
};
int main()
{
Foo<double> fd;
fd.foo(); // OK
//fd.bar(); // ERROR: bar() only works with Foo<int>
Foo<int> fi;
fi.foo(); // OK
fi.bar(); // OK
}
或者,您可以使用SFINAE
来控制所涉及方法的类型。
template <typename T>
class Foo
{
public:
void foo() const {}
template<typename T2 = T,
typename = typename std::enable_if<std::is_same<T, int>::value>::type>
void bar() {}
};
请参阅此相关问题。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句