struct TypeA {
using data_t = int;
enum { thread_create = pthread_create }; // ???
};
struct TypeB {
using data_t = double;
enum { thread_create = another_kind_of_thread_create }; // ???
};
template<typename T>
class Test {
public:
void func() {
T::thread_create(); // ???
}
private:
T::data_t a;
};
Test<TypeA> t1;
Test<TypeB> t2;
我要做的是Test用一個模板引數專門化模板類。
如您所見,data_t應該沒有任何問題,但傳遞函式似乎并不容易。這段代碼會產生錯誤:error: enumerator value for 'thread_create' must have integral or unscoped enumeration type.
是否可以傳遞這樣的函式?
uj5u.com熱心網友回復:
我如果理解正確,您想根據專業化切換執行緒創建功能和資料型別。如果是這樣,為什么不這樣呢?
#include <type_traits>
void pthread_create(void*, void*);
void another_kind_of_thread_create(void*, void*);
//my fakes. use your includes here
struct TypeA {
using data_t = int;
using thread_create_t = void (*)(void*, void*);
static constexpr thread_create_t thread_create{pthread_create};
};
struct TypeB {
using data_t = double;
using thread_create_t = void (*)(void*, void*);
static constexpr thread_create_t thread_create{another_kind_of_thread_create};
};
template<typename T>
class Test : public T {
public:
void func() {
T::thread_create(this, &a); //whatever, put here just to match the prototype...
}
private:
typename T::data_t a;
};
Test<TypeA> t1;
Test<TypeB> t2;
static_assert(std::is_same<decltype(t1)::data_t, int>::value, "t1 should be int");
static_assert(std::is_same<decltype(t2)::data_t, double>::value, "t2 should be double");
演示
uj5u.com熱心網友回復:
您正在描述一個非常普通的特征類。您可能正在尋找以下方面的內容:
struct TypeA {
using data_t = int;
static void thread_create() { pthread_create() };
};
這將允許T::thread_create();語法。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/410162.html
標籤:
