何时指定模板函数的模板参数?

时间:2018-03-04 13:02:36

标签: c++ linux templates g++

编译以下内容时:

var settings = new ConnectionSettings(new Uri("http://distribution.virk.dk/cvr-permanent"));
var client = new ElasticClient(settings);
// get mappings for all indexes and types
var mappings = client.GetMapping<JObject>(c => c.AllIndices().AllTypes());
foreach (var indexMapping in mappings.Indices) {
    Console.WriteLine($"Index {indexMapping.Key.Name}"); // index name
    foreach (var typeMapping in indexMapping.Value.Mappings) {
        Console.WriteLine($"Type {typeMapping.Key.Name}"); // type name
        foreach (var property in typeMapping.Value.Properties) { 
            // property name and type. There might be more useful info, check other properties of `typeMapping`
            Console.WriteLine(property.Key.Name + ": " + property.Value.Type);
            // some properties are themselves objects, so you need to go deeper
            var subProperties = (property.Value as ObjectProperty)?.Properties;
            if (subProperties != null) {
                // here you can build recursive function to get also sub-properties
            }
        }
    }
}

我明白了:

#include <iostream>

class A {
public:
    template <class X, class Y>
    void foo(X& x, Y& y) {
        x.bar<Y>(y);
    }
};

class B {
public:
    template <class Z>
    void bar(Z& z) {
        std::cout << __PRETTY_FUNCTION__ << std::endl;
    }
};

class C {
};

int main() {
    A a;
    B b;
    C c;
    a.foo<B, C>(b, c);
}

如果我没有指定模板参数并让GCC推导出B :: bar()的模板参数,GCC很乐意编译它。

首先,我想,这意味着如果编译器可以推导出它,我不应该为模板成员函数指定模板参数。

但是,当我调用a.foo()时,编译器也应该能够推导出模板参数。但编译器并没有抱怨。

因此,当为模板成员函数指定模板参数是非法的时,我很困惑,当它是必须的时候。

提前致谢。

P.S。我正在使用g ++ 7.2.1。

0 个答案:

没有答案