我试图创建一个类,它应该从其他类继承构造函数,但不从这些类本身继承.
在我的类初始化期间的某个时刻,我想使用完美转发来创建一个类型的对象,其构造函数与给定的参数匹配.
除了没有参数的默认构造函数之外,不存在歧义.
这是我的代码:
#include <string>
using namespace std;
//NOTE: this class is just an example to demonstrate the problem
class String {
public:
//default constructor to prevent ambiguity
String() {}
//construct from wstring
template<typename... Args>
String(enable_if<is_constructible<wstring, Args...>::value, Args>::type&&... args) : ws(forward<Args>(args)...) {}
//construct from string
template<typename... Args>
String(enable_if<is_constructible<string, Args...>::value, Args>::type&&... args) : s(forward<Args>(args)...) {}
private:
string s;
wstring ws;
};
void foo(const String& string) {
}
int main()
{
foo(L"123");
foo("123");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我尝试过很多东西,但我无法让它发挥作用.
enable_if无法自动扣除模板args(我认为)我已经添加了一个子目录CMake使用add_subdirectory.如何通过set与PARENT_SCOPE?结合使用来显式设置变量,从该子目录的范围访问变量?
set(BOX2D_BUILD_STATIC 1)
set(BOX2D_BUILD_EXAMPLES 0)
set(BOX2D_INSTALL_BY_DEFAULT 0)
add_subdirectory(Box2D_v2.2.1)
message(STATUS "Using Box2D version ${BOX2D_VERSION}")
# how to get ${BOX2D_VERSION} variable without modifying CMakeLists.txt in Box2D_v2.2.1?
Run Code Online (Sandbox Code Playgroud)
这可能吗?
我试图用来std::is_function确定变量是否是一个函数指针.
运行以下代码时
#include <iostream>
#include <typeinfo>
using namespace std;
int main() {
typedef int(*functionpointer)();
functionpointer pmain = main;
cout << typeid(functionpointer).name() << " "<< is_function<functionpointer>::value << endl;
cout << typeid(decltype(pmain)).name() << " " << is_function<decltype(pmain)>::value << endl;
cout << typeid(decltype(main)).name() << " " << is_function<decltype(main)>::value << endl;
cout << typeid(decltype(*pmain)).name() << " " << is_function<decltype(*pmain)>::value << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出是
PFivE 0
PFivE 0
FivE 1
FivE 0
Run Code Online (Sandbox Code Playgroud)
任何有洞察力的人std::is_function都能解释为什么最后一个表达式的评估为假吗?
(在g ++ 4.7,g ++ 4.8和clang ++ …
我试图了解强制转换操作符如何使用模板.
请考虑以下代码:
#include <iostream>
using namespace std;
struct S {
int v;
};
class A {
public:
A(void* ptr) : ptr(ptr) {}
void* ptr;
template<typename T>
const T& as() const {
return *static_cast<T*>(ptr);
}
template<typename T>
operator const T&() const {
return as<T>();
}
};
int main() {
S test;
test.v = 123;
A a(&test);
S s = a.as<S>();
S s2 = a; // error here
const S& s3 = a;
cout << s.v << endl;
cout << s2.v << …Run Code Online (Sandbox Code Playgroud)