簡體   English   中英

如何使用非類型模板參數和類型模板參數的混合來模板化函數?

[英]How to template a function with a mix of non-type template parameters and type template parameters?

最小可重復示例

#include <unordered_map>
#include <string>

template<class T, bool did_work>
class Test {
    Test(T input) : field(input), success(did_work) {}
    T field;
    bool success;
};

template<typename A>
void func(std::unordered_map<std::string, Test<A, bool>> input1, A input2) {}

int main() {}

輸出:

$ g++ -std=c++17 -ggdb -g3 -Wall test.cpp && ./a.out 
test.cpp:12:51: error: type/value mismatch at argument 2 in template parameter list for ‘template<class T, bool did_work> class Test’
   12 | void func(std::unordered_map<std::string, Test<A, bool>> input1, A input2) {}
      |                                                   ^~~~
test.cpp:12:51: note:   expected a constant of type ‘bool’, got ‘bool’
test.cpp:12:55: error: template argument 2 is invalid
   12 | void func(std::unordered_map<std::string, Test<A, bool>> input1, A input2) {}
      |                                                       ^~
test.cpp:12:55: error: template argument 5 is invalid

我需要能夠傳入unordered_map<std::string, Test<A, true>>以及unordered_map<std::string, Test<A, false>> 有沒有辦法在不更改類Test定義的情況下在函數定義中執行此操作?

使用template<class T, bool did_work> did_work是非類型模板參數。 這意味着它不是將類型傳遞給它,而是需要一個值。 由於它需要一個值,因此您可以進行Test Test<A, true>Test<A, false> Test<A, bool> ,而不是Test<A, bool>

對於您的功能,您只需添加一個非類型模板參數即可為您執行此操作

template<typename A, bool did_work>
void func(std::unordered_map<std::string, Test<A, did_work>> input1, A input2) {}

像這樣做:

#include <unordered_map>
#include <string>

template<class T, bool did_work>
class Test {
    Test(T input) : field(input), success(did_work) {}
    T field;
    bool success;
};

template<typename A, bool b = true>
void func(std::unordered_map<std::string, Test<A, b>> input1, A input2)
{

}

int main() {

}

更新

我的意思是你寫這樣的東西:

#include <unordered_map>
#include <string>
#include <iostream>

template<class T, bool did_work>
class Test {
public:
    Test(T input) : field(input), success(did_work) {}
private:
    T field;
    bool success;
};

template<
    typename UnorderedMap
    ,typename A
> requires requires (UnorderedMap map){
    map.size();
}
void func(
    UnorderedMap input1,
    A input2)
{
    std::cout << input1.size();
}

int main() 
{
    using A = int;
    Test<A, true> t{12};
    std::unordered_map<std::string, Test<A, true>> map{};
    func(map, 12);

    //this would fail!
    //func(12, 12);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM