簡體   English   中英

C ++模板無法理解的行為

[英]C++ template incomprehensible behaviour

首先-該代碼很糟糕,我知道,它是為嘗試模板而設計的,但是我真誠地不知道它如何/為什么如顯示的那樣工作。

編碼:

#include <iostream>
#include <vector>
#include <string>

template <typename T>
class Container {
public:
    Container() { 
        std::cout << "Container()" << std::endl;
    }
    Container(const Container& other){
        std::cout << "Container(const Container& other)" << std::endl;
    }
    template <typename A>
    Container(const A& other) {
        std::cout << "Container(const A& other)" << std::endl;
    }
    Container(const std::vector<int>& other) { 
        std::cout << "Container(const std::vector<int>& other)" << std::endl;
    }
    ~Container() { 
        std::cout << "~Container()" << std::endl;
    }
};

int main(){
    Container<int> c1;
    Container<int> c2(c1);
    Container<int> c3(std::vector<int>());
    Container<int> c4();
    Container<int> c3(std::string());

    return 0;
}

輸出:

Container()
Container(const Container& other)
Container()
~Container()
~Container()
~Container()

問題是:

  1. 它編譯! (使用-Wall,-Wextra僅顯示未使用的其他參數)為什么?
  2. 它運行! (我可能會想到一些UB,但我不知道其起源)。 為什么?

這里發生了什么事? 為什么c3變量似乎被完全忽略了? 我有點主意,也許它不能擴展模板,但是為什么在編譯時它不會失敗?

編譯器:gcc版本4.8.1

由於兩個c3變量都是真正的函數聲明(如Angew在評論中指出的那樣),因此您最終將聲明重載函數。

您聲明了一個帶有std::vector<int>()參數的重載,以及一個帶有std::string()參數的重載。 這兩個重載不沖突,並且代碼可以編譯。

如前所述:c3,c4和c5是函數聲明,但沒有人說如何解決。

Container<int> c3((std::vector<int>())); // add parentheses to clarify it's not a function declaration
Container<int> c4; // remove parentheses
Container<int> c3((std::string())); // add parentheses

暫無
暫無

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

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