[英]How can we check the type of the template parameter in c++?
在java中,我們可以指定參數的類型
public <T extends SomeInterface> void genericMethod(Set<? extends T> tSet) {
// Do something
}
它寫成T extends SomeInterface
。 這個功能是否受c ++支持?
聽起來像你想要這樣的東西:
template <class T>
std::enable_if_t<std::is_base_of<SomeInterface, T>::value, void>
genericMethod(std::set<T> tSet)
{
// Do something
}
如果你能詳細說明什么Set<? extends T> tSet
Set<? extends T> tSet
意味着,那么我相信我們也可以合並它。
您可以通過以下兩種方式之一完成此操作,此處最簡單的解決方案是使用表示接口的基類指針。 在此之后,您只能將指針傳遞給從該基類派生的對象。 所以這樣的事情
#include <iostream>
#include <string>
using std::cout;
using std::endl;
class BaseOne {};
class BaseTwo {};
class DerivedOne : public BaseOne {};
class DerivedTwo : public BaseTwo {};
void foo(BaseOne*) {
cout << __PRETTY_FUNCTION__ << endl;
}
void foo(BaseTwo*) {
cout << __PRETTY_FUNCTION__ << endl;
}
int main() {
auto derived_one = DerivedOne{};
auto derived_two = DerivedTwo{};
foo(&derived_one);
foo(&derived_two);
}
或者如果目標是在沒有基類的編譯時執行此操作,即沒有繼承和沒有概念(預計會出現在C ++ 20中\\ _(ツ)_ /¯)並且只檢查某些存在方法,然后你可以做這樣的事情
#include <iostream>
#include <type_traits>
using std::cout;
using std::endl;
struct One { void one() {} };
struct Two { void two() {} };
/**
* Loose SFINAE based concepts
*/
template <typename Type, typename T = std::decay_t<Type>>
using EnableIfOne = std::enable_if_t<std::is_same<
decltype(std::declval<T>().one()), decltype(std::declval<T>().one())>
::value>;
template <typename Type, typename T = std::decay_t<Type>>
using EnableIfTwo = std::enable_if_t<std::is_same<
decltype(std::declval<T>().two()), decltype(std::declval<T>().two())>
::value>;
template <typename T, EnableIfOne<T>* = nullptr>
void foo(T&) {
cout << __PRETTY_FUNCTION__ << endl;
}
template <typename T, EnableIfTwo<T>* = nullptr>
void foo(T&) {
cout << __PRETTY_FUNCTION__ << endl;
}
int main() {
auto one = One{};
auto two = Two{};
foo(one);
foo(two);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.