是否可以编写一个模板来改变行为,具体取决于是否在类上定义了某个成员函数?
这是我想写的一个简单例子:
template<class T>
std::string optionalToString(T* obj)
{
if (FUNCTION_EXISTS(T->toString))
return obj->toString();
else
return "toString not defined";
}
Run Code Online (Sandbox Code Playgroud)
所以,如果class T已经toString()确定的话,就使用它; 否则,它没有.我不知道怎么做的神奇部分是"FUNCTION_EXISTS"部分.
我是否可以编写一个带有参数T的模板函数,foo如果它存在T,则调用成员函数,如果它不调用自由函数foo(T)(如果两者都不存在则无法编译)?
就像是:
template<typename T>
int call_foo(T t) {
// if T::foo() exists
return t.foo();
// else return foo(t);
}
Run Code Online (Sandbox Code Playgroud)
相反的情况怎么样:foo在成员函数之前更喜欢自由函数?我不能使用C++ 11之后引入的任何功能.
我正在尝试编写像这里的代码,但使用C++ 11功能,没有Boost.
在这个例子中,我尝试response_trait在特征的结果上定义一个和basee条件编译.我怎样才能做到这一点?
#include <vector>
using namespace std ;
struct Vector{ float x,y,z ; } ;
struct Vertex { Vector pos ; } ;
struct VertexN { Vector pos, normal ; } ;
struct Matrix {} ;
template <typename T>
struct response_trait {
static bool const has_normal = false;
} ;
template <>
struct response_trait<VertexN> {
static bool const has_normal = true;
} ;
template <typename T>
struct Model
{
vector<T> verts …Run Code Online (Sandbox Code Playgroud) 我对SFINAE有基本的了解,比如说enable_if有效.我最近遇到了这个答案,我花了一个多小时试图了解它实际上是如何工作无济于事的.
此代码的目标是根据类中是否包含特定成员来重载函数.这是复制的代码,它使用C++ 11:
template <typename T> struct Model
{
vector<T> vertices;
void transform( Matrix m )
{
for(auto &&vertex : vertices)
{
vertex.pos = m * vertex.pos;
modifyNormal(vertex, m, special_());
}
}
private:
struct general_ {};
struct special_ : general_ {};
template<typename> struct int_ { typedef int type; };
template<typename Lhs, typename Rhs,
typename int_<decltype(Lhs::normal)>::type = 0>
void modifyNormal(Lhs &&lhs, Rhs &&rhs, special_) {
lhs.normal = rhs * lhs.normal;
}
template<typename Lhs, typename Rhs>
void modifyNormal(Lhs …Run Code Online (Sandbox Code Playgroud) 这是我有点奇怪的代码:
template <typename T&>
class A {
public:
void b(typename std::enable_if<!std::is_pointer<T>::value, T>;::type o) {}
void b(typename std::enable_if<std::is_pointer<T>::value, T>;::type o) {}
};
template <typename T>
void b(typename std::enable_if<!std::is_pointer<T>::value, T>::type o) {}
template <typename T>
void b(typename std::enable_if<std::is_pointer<T>::value, T>::type o) {}
Run Code Online (Sandbox Code Playgroud)
如果我ifdef出了方法b和呼叫b<int *>(pi),其中pi是int *,一切编译.
如果我ifdef退出函数b(外部类)并调用A<int *> a; a.b(pi),我会收到以下错误:
error: no type named 'type' in 'std::__1::enable_if<false, int *>'
为什么不一致以及如何解决问题以便我可以使用A中的方法?